import React from "react";
import type { Meta, StoryObj } from "@storybook/react-webpack5";
import { AutoComplete, AutoCompleteProps, DataSourceType } from "./autoComplete";

const meta: Meta<typeof AutoComplete> = {
  title: "Components/AutoComplete",
  component: AutoComplete,
  tags: ["autodocs"],
  parameters: {
    layout: "centered",
  },
  argTypes: {
    placeholder: { control: "text" },
    debounce: { control: { type: "number", min: 0, max: 1000, step: 50 } },
    disabled: { control: "boolean" },
  },
};

export default meta;
type Story = StoryObj<typeof AutoComplete>;

// 同步建议示例
export const Basic: Story = {
  name: "同步建议",
  render: (args) => {
    // 本地的城市列表
    const cities = ["北京", "上海", "广州", "深圳", "杭州", "成都", "南京", "苏州", "天津", "重庆"];
    const fetchSuggestions: AutoCompleteProps["fetchSuggestions"] = (q) => {
      const res = cities
        .filter((c) => c.includes(q))
        .map((c) => ({ value: c })) as DataSourceType[];
      return res;
    };
    return <AutoComplete {...args} placeholder="输入城市" fetchSuggestions={fetchSuggestions} />;
  },
};

// 异步建议示例
export const Async: Story = {
  name: "异步建议",
  render: (args) => {
    const fetchSuggestions: AutoCompleteProps["fetchSuggestions"] = async (q) => {
      // 模拟异步请求
      await new Promise((r) => setTimeout(r, 400));
      return ["apple", "banana", "orange", "grape", "watermelon", "pineapple"]
        .filter((i) => i.includes(q))
        .map((i) => ({ value: i }));
    };
    return <AutoComplete {...args} placeholder="输入水果" fetchSuggestions={fetchSuggestions} />;
  },
};

// 自定义渲染示例
export const CustomRender: Story = {
  name: "自定义模板",
  render: (args) => {
    const books = [
      { title: "JavaScript 高级程序设计", author: "Nicholas C. Zakas" },
      { title: "你不知道的 JavaScript", author: "Kyle Simpson" },
      { title: "React 设计原理", author: "Mark Erikson" },
    ];
    const fetchSuggestions: AutoCompleteProps["fetchSuggestions"] = (q) => {
      return books
        .filter((b) => b.title.includes(q))
        .map((b) => ({ value: b.title, data: b }));
    };
    const renderOption: AutoCompleteProps["renderOption"] = (item) => {
      const info = item.data as { title: string; author: string } | undefined;
      return (
        <div style={{ display: "flex", flexDirection: "column" }}>
          <strong>{item.value}</strong>
          {info?.author && <span style={{ color: "#888" }}>{info.author}</span>}
        </div>
      );
    };
    return (
      <AutoComplete
        {...args}
        placeholder="输入书名"
        fetchSuggestions={fetchSuggestions}
        renderOption={renderOption}
      />
    );
  },
};